package com.esun.cheetah.view.personal.sportlotteryfootball;

import java.text.Format;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.personalcommunicater.PersonalLoginCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.view.personal.RegistAct;
import com.esun.cheetah.view.setting.UserSuggestAct;
import com.esun.cheetah.view.setting.ValuesManager;
import com.esun.cheetah.view.setting.com.SetCommu;
import com.esun.util.EditTextInputUitl;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

/**
 * 
 * @Package com.esun.cheetah.view.personal.LoginAct
 * @ClassName: LoginAct
 * @Description: TODO(user login interface)
 * @author hxt <br/>
 * @date create at 2012-3-29 下午8:02:10
 * 
 */

public class LoginBetAct extends Activity implements OnClickListener,
		TextView.OnEditorActionListener {
	/** Called when the activity is first created. */
	private Button btnLogin; // 登錄按鈕

	private int Flag;//1购彩  0 活动
	private ImageButton ibCancel;// 取消
	private Button btnRegist; // 注册..
	private Button btnCleanUserName; // 清空用户名..
	private Button btnCleanUserPass; // 清空密码..

	private EditText edtUserName; // 输入用户名
	private EditText edtUserPass; // 输入密码

	private Handler handler;


	/** 时间日期装换 */
	public static Format format = new SimpleDateFormat("yyyyMMdd");

	/** 设置值的管理类 */
	private ValuesManager valuesManager;
	private String strUserName;// 输入的用户名
	private String strUserPass;// 输入的密码
	private String strUserPassMD5;// 转为md5
	private ProgressDialog loginDialog;
	private long loginTime;// 登陆时间
	private String shareUserName;// 保存的用户名
	private String shareUserpass;// 保存的密码
	private SharedPreferences sharedPreferences;
	private PersonalLoginCommunicater personallogincommunicater;
	private ProgressDialog progressDialog;

	private InputMethodManager mInputMethodManager;

	/** 设置值的handler */
	Handler setHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		setContentView(R.layout.loginbet);

		uiInit();
		initHandler();
		loginDialog = new ProgressDialog(LoginBetAct.this);
		progressDialog = ViewerUtil.showProgressDialog(LoginBetAct.this,
				Language.MSG_LOADING);

	}

	private void uiInit() {
		Intent intent = getIntent();
		String num1 = intent.getStringExtra("flag");
		EDebug.o("---------------n======um1" + num1);
		Flag = Integer.parseInt(num1);

		valuesManager = new ValuesManager(this);

		btnLogin = (Button) findViewById(R.id.loginact_btn_login);
		btnLogin.setOnClickListener(this);

		ibCancel = (ImageButton) findViewById(R.id.cancel_btn);
		ibCancel.setOnClickListener(this);

		btnRegist = (Button) findViewById(R.id.loginact_btn_regist);
		btnRegist.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.loginact_edt_userName);

		btnCleanUserName = (Button) findViewById(R.id.loginact_btn_claenUserNmae);
		edtUserName = new EditTextInputUitl(edtUserName, btnCleanUserName)
				.getEditText();

		edtUserPass = (EditText) findViewById(R.id.loginact_edt_userPass);
		btnCleanUserPass = (Button) findViewById(R.id.loginact_btn_claenUserPass);
		edtUserPass = new EditTextInputUitl(edtUserPass, btnCleanUserPass)
				.getEditText();

		edtUserName.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View arg0, boolean arg1) {
				if (arg0.isFocused()) {
					mInputMethodManager.showSoftInput(arg0, 0);
				} else {
					mInputMethodManager.hideSoftInputFromWindow(
							edtUserName.getWindowToken(), 0);
				}
			}
		});
		edtUserPass.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View arg2, boolean arg3) {
				if (arg2.isFocused()) {
					mInputMethodManager.showSoftInput(arg2, 0);
				} else {
					mInputMethodManager.hideSoftInputFromWindow(
							edtUserPass.getWindowToken(), 0);
				}
			}
		});

	}

	private void initHandler() {

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					if (Flag == 1) {
						Message msgToGroup = SportteryFootballChooseList.handlerChoosePage
								.obtainMessage(
										SportteryFootballChooseList.LOG_SUCCEED,
										null);
						SportteryFootballChooseList.handlerChoosePage
								.sendMessage(msgToGroup);
					}else if(Flag == 0)  {
						Intent intent = new Intent();

						intent.setClass(LoginBetAct.this, UserSuggestAct.class);
						startActivity(intent);
					}else{
					  EDebug.o("nothing");   
					}
					
					if (null == shareUserName && null == shareUserpass) {
						saveSharedPreferences();
					} else {
						saveUsedSharedPreferences();
					}

					saveUserInfo();
					// gotoLoggedinAct();
					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}
					closeDialog();
					hideSoftKey();
					LoginBetAct.this.finish();
					break;
				case Config.COMMUNICATER_FAIL:
					Toast.makeText(LoginBetAct.this,
							personallogincommunicater.getServerMsg(), 500)
							.show();
					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}
					closeDialog();
					break;
				case Config.COMMUNICATER_EXCEPTION:
					Toast.makeText(LoginBetAct.this, Language.NERWORK_ABORT,
							500).show();
					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());
					closeDialog();
					break;
				}
			}
		};

	}

	protected void saveUsedSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(Key.KEY_USERNAME, shareUserName);
		editor.putString(Key.SAVE_PASSWORD, shareUserpass);
		editor.commit();
		EDebug.o("save strUserName2--" + shareUserName);
		EDebug.o("save strUserPassMD52--" + shareUserpass);
	}

	private void closeDialog() {
		if (loginDialog.isShowing()) {
			loginDialog.cancel();
		} else {
			EDebug.o("nodialog");
		}
	}

	private void saveUserInfo() {
		loginTime = System.currentTimeMillis();
		UserInfo.getUserInfo().setLogintime(loginTime);
		EDebug.o("logintime------" + loginTime);
	}

	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.loginact_btn_login:
				// 验证输入限制条件
				if (!edtUserName.getText().equals(null)
						&& edtUserName.getText().toString().length() < Language.NUM_ONE) {
					EDebug.o("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
					// ViewerUtil.showTipDialog(LoginBetAct.this,
					// Language.ENTER_USERNAME, false);
					Toast.makeText(LoginBetAct.this, Language.ENTER_USERNAME,
							500).show();
				} else if (!edtUserPass.getText().equals(null)
						&& edtUserPass.getText().toString().length() < Language.NUM_ONE) {
					// ViewerUtil.showTipDialog(LoginBetAct.this,
					// Language.ENTER_LOGIN_PASSWORD, false);
					Toast.makeText(LoginBetAct.this,
							Language.ENTER_LOGIN_PASSWORD, 500).show();
				} else if (edtUserName.getText().toString().length() < Language.NUM_FOUR
						|| edtUserName.getText().toString().length() > Language.NUM_SIXTEEN) {
					// ViewerUtil.showTipDialog(LoginBetAct.this,
					// Language.ENTER_RIGHT_USERNAME, false);
					Toast.makeText(LoginBetAct.this,
							Language.ENTER_RIGHT_USERNAME, 500).show();
				} else if (edtUserPass.getText().toString().length() < Language.NUM_SIX
						|| edtUserPass.getText().toString().length() > Language.NUM_FIVETEEN) {
					// ViewerUtil.showTipDialog(LoginBetAct.this,
					// Language.ENTER_RIGHT_PASSWORD, false);
					Toast.makeText(LoginBetAct.this,
							Language.ENTER_RIGHT_PASSWORD, 500).show();
				} else {
					getInputInfo();

//					if (Flag == 1) {
//						startcommunicatlogin(huodonghandler, strUserName,
//								strUserPassMD5, this);
//						showloginDialog();
//					} else {
						startcommunicatlogin(handler, strUserName,
								strUserPassMD5, this);
						showloginDialog();
//					}

				}
				break;
			case R.id.loginact_btn_regist:
				gotoRegistAct();
				break;
			case R.id.loginact_btn_claenUserNmae:
				edtUserName.setText(Config.NULLMARK);
				break;
			case R.id.cancel_btn:
				// Message msgToGroup =
				// SportteryFootballChooseList.handlerChoosePage
				// .obtainMessage(SportteryFootballChooseList.CANCALE,null);
				// SportteryFootballChooseList.handlerChoosePage
				// .sendMessage(msgToGroup);
				// int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
				// getWindow().addFlags(flags);

				// mInputMethodManager.hideSoftInputFromWindow(
				// arg2, 0);

				// mInputMethodManager.
				hideSoftKey();
				this.finish();

				break;

			case R.id.loginact_btn_claenUserPass:
				edtUserPass.setText(Config.NULLMARK);
				break;

			default:
				break;
			}
		} catch (Exception e) {
			String str = e.toString();
			Log.e("--", str);
			// TODO: handle exception
		}
	}

	// private void gotoLoggedinAct() {
	// intentToSportteryFootball = new Intent();
	// intentToSportteryFootball
	// .setClass(
	// LoginBetAct.this,
	// com.esun.cheetah.view.personal.sportlotteryfootball.SportteryFootballAgp.class);
	// bundleToSportteryFootbal = new Bundle();
	// bundleToSportteryFootbal.putInt("CURRENT_TAB_NUM", 0);
	// intentToSportteryFootball.putExtras(bundleToSportteryFootbal);
	// EDebug.o(this, "click to shuangseqiu choose");
	// startActivity(intentToSportteryFootball);
	// LoginBetAct.this.finish();
	// }

	private void saveSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(Key.KEY_USERNAME, strUserName);
		editor.putString(Key.SAVE_PASSWORD, strUserPassMD5);
		editor.commit();
		EDebug.o("save strUserName--" + strUserName);
		EDebug.o("save strUserPassMD5--" + strUserPassMD5);
	}

	private void gotoRegistAct() {
		Intent registIntent = new Intent();
		registIntent.setClass(LoginBetAct.this, RegistAct.class);
		startActivity(registIntent);
		LoginBetAct.this.finish();
	}

	private void showloginDialog() {
		loginDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		loginDialog.setMessage(Language.LOGGING);
		loginDialog.setIndeterminate(false);// 设置进度条是否为不明确
		loginDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
		loginDialog.show();
	}

	private void startcommunicatlogin(Handler handler, String username,
			String userpass, Context context) {
		personallogincommunicater = new PersonalLoginCommunicater(handler,
				username, userpass, context);
		personallogincommunicater.startCommunicate();
		new SetCommu(setHandler, this, valuesManager.getBeginTime(),
				valuesManager.getEndTime()).startCommunicate();
		// openNotice();
	}

	private void getInputInfo() {
		strUserName = edtUserName.getText().toString();
		strUserPass = edtUserPass.getText().toString();
		strUserPassMD5 = MD5.md5(strUserPass);
		EDebug.o("strUserName---------------" + strUserName);
		EDebug.o("strUserPass---------------" + strUserPass);
		EDebug.o("handler---------------" + handler);
	}

	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		return true;
	}

	private void hideSoftKey() {

		mInputMethodManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		mInputMethodManager.hideSoftInputFromWindow(
				edtUserName.getWindowToken(), 0);

	}

}
